package com.webTest.Dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.webTest.Bean.PageBean;
import com.webTest.Bean.Product;
import com.webTest.Bean.Type;

@Repository("productDao")
public class ProductDaoImpl implements ProductDao {
	private Session session;  
	
	public  SessionFactory sessionFactory;
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public Session getCurrentSession() {  
        if(session!=null)  
            return session;  
        return sessionFactory.getCurrentSession();  
    }  

	@SuppressWarnings("unchecked")
	@Override
	public List<Product> getProductList(Product s_product, PageBean pageBean) {
		List<Product> list=new ArrayList<Product>();
		String hql="from Product where flag=1";
		Query q=this.getCurrentSession().createQuery(hql);
		list=q.setFirstResult(pageBean.getStart()).setMaxResults(pageBean.getPageSize()).list();
		return list;
	}

	@Override
	public Long getProductCount(Product s_product) {
		String hql="SELECT COUNT(*) FROM Product where flag=1";
		Query q = this.getCurrentSession().createQuery(hql);  
		Long long1=(Long) q.uniqueResult();
		return long1;
	}

	@Override
	public void saveProduct(Product product) {
		this.getCurrentSession().merge(product);

	}

	@Override
	public Product getID(int id) {
		Product product=new Product();
		product.setId(id);
		product=(Product) this.getCurrentSession().get(Product.class, product.getId());
		return product;
		
	}

	@Override
	public void deletProduct(Product product) {
		String hql = "update Product set flag=0 where id="+product.getId();
		this.getCurrentSession().createQuery(hql).executeUpdate();
//		this.getCurrentSession().delete(product);
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Product> getProductTID(int tid) {
		List<Product> list=new ArrayList<Product>();
		String hql="from Product where tid='"+tid+"'";
		Query q=this.getCurrentSession().createQuery(hql);
		list=q.list();
		return list;
		
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<Type> getTypeTID(int pid) {
		List<Type> list=new ArrayList<Type>();
		String hql="from Type where pid='"+pid+"'";
		Query q=this.getCurrentSession().createQuery(hql);
		list=q.list();
		return list;
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<Product> getAllProduct() {
		String hql="from Product where flag=1";
		return this.getCurrentSession().createQuery(hql).list();
	}

}
